import React, { PureComponent } from 'react';
import { Form, Input, Button, Alert, Divider, Spin } from 'antd';
import { routerRedux } from 'dva/router';
import { connect } from 'dva';
import styles from './style.less';

@connect(state => ({
  attrList: state.assetType.typeAttr,
  loading: state.assetType.loading,
  stepData: state.assetEntity.step,
}))
@Form.create()
export default class Step2 extends PureComponent {
  // back to prev step
  onPrev = () => {
    const { dispatch } = this.props;
    dispatch(routerRedux.push('/asset/add'));
  }
  // validate forms
  onValidateForm = (e) => {
    e.preventDefault();
    const { dispatch, form, stepData } = this.props;
    const { validateFields } = form;
    validateFields((err, values) => {
      if (!err) {
        dispatch({
          type: 'assetEntity/submitAssetEntity',
          payload: {
            ...stepData,
            step2: values,
          },
        });
      }
    });
  }

  render() {
    const { form, attrList, formItemLayout } = this.props;
    const { getFieldDecorator } = form;
    return (
      <Form layout="horizontal" className={styles.stepForm}>
        <Alert
          closable
          showIcon
          message="资产属性根据资产类型定义，如果属性不符，请重新选择资产类型"
          style={{ marginBottom: 24 }}
        />
        {attrList.length > 0 ? attrList.map((attr) => {
          return (
            <Form.Item
              {...formItemLayout}
              key={attr.id}
              label={attr.attr_name}
              className={styles.stepFormText}
            >
              {getFieldDecorator(`${attr.attr_id}`, {
                rules: [{ required: true, message: `请填写${attr.attr_name}` }],
              })(
                <Input placeholder={`请填写${attr.attr_name}`} />
                )}
            </Form.Item>
          );
        }) : (
          <Spin size="small" style={{ marginLeft: 8 }} />
          )}
        <Divider style={{ margin: '24px 0' }} />
        <Form.Item
          style={{ marginBottom: 8 }}
          wrapperCol={{
            xs: { span: 24, offset: 0 },
            sm: { span: formItemLayout.wrapperCol.span, offset: formItemLayout.labelCol.span },
          }}
        >
          <Button type="primary" onClick={this.onValidateForm} loading={this.loading}>
            提交
          </Button>
          <Button onClick={this.onPrev} style={{ marginLeft: 8 }}>
            上一步
          </Button>
        </Form.Item>
      </Form>
    );
  }
}

